package cn.catfish.service.impl;

import cn.catfish.config.BooksException;
import cn.catfish.entity.Book;
import cn.catfish.entity.BookStatus;
import cn.catfish.entity.BorrowRecord;
import cn.catfish.entity.User;
import cn.catfish.mapper.BookMapper;
import cn.catfish.mapper.RecordMapper;
import cn.catfish.mapper.UserMapper;
import cn.catfish.service.BookService;
import cn.catfish.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RecordMapper recordMapper;
    @Override
    public List<Book> findAllBooks() {
        return bookMapper.getAllBooks();
    }

    @Override
    public Book getBookById(int id) {
        return bookMapper.getBookById(id);
    }

    @Override
    public Book getBookName(String title) {
        return bookMapper.getBookName(title);
    }

    @Override
    public boolean borrowBook(User user, Book book) throws BooksException {
         List<BorrowRecord> a = recordMapper.getRecordsByUserId(user.getUserid());
        if (book.getStatus() == BookStatus.AVAILABLE
                && book.getStock() > 0 && a.size() < 5) {
            book.setStock(book.getStock() - 1);
            if (book.getStock() == 0) {
                book.setStatus(BookStatus.BORROWED);
            }
            return true;
        }
        return false;
    }
    @Override
    public boolean returnBook(int userid, int id, long overdueDays) {
       User user = userMapper.findById(userid);
       Book book = bookMapper.getBookById(id);
      if (user == null) {
          System.out.println("用户不存在");
          return false;
      }
      if (book == null) {
          System.out.println("图书不存在");
          return false;
      }
       book.setStock(book.getStock() + 1);
       book.setStatus(BookStatus.AVAILABLE);
        System.out.println(user.getMoney());
       user.setMoney(user.getMoney() - (float) overdueDays * 1);
        System.out.println(user.getMoney());
       userMapper.update(user);
        System.out.println(user);
       bookMapper.updateBook(book);
       return true;
    }

    @Override
    public boolean addBook(Book book) {
        Book bookInDB = bookMapper.getBookById(book.getId());
        if (bookInDB == null && bookInDB.getTitle().equals(book.getTitle())) {
            throw new BooksException("BOOK_ALREADY_EXISTS");
        }
        bookMapper.insertBook(book);
        return true;
    }

    @Override
    public void updateBook(Book book) {
        bookMapper.updateBook(book);
        return;
    }

}
